﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.SmallProject.SnowFlake
{
    public class Snowflake1
    {
        //第一位
        private static int FIRST_BIT = 0;
        //初始时间截 (2017-01-01)
        private static long INITIAL_TIME_STAMP = 1483200000000L;
        //数据标识id所占的位数
        private static int DATACENTER_ID_BITS = 5;
        //机器id所占的位数
        private static int WORKER_ID_BITS = 5;
        //支持的最大机器id，结果是31 
        //(这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
        private static long MAX_WORKER_ID = ~(-1 << WORKER_ID_BITS);
        //支持的最大数据标识id，结果是31
        private static long MAX_DATACENTER_ID = ~(-1 << DATACENTER_ID_BITS);
        //序列在id中占的位数
        private static int SEQUENCE_BITS = 12;
        //机器ID的偏移量(12)
        private static int WORKERID_OFFSET = SEQUENCE_BITS;
        //数据中心ID的偏移量(12+5)
        private static int DATACENTERID_OFFSET = SEQUENCE_BITS + SEQUENCE_BITS;
        //时间截的偏移量(5+5+12)
        private static int TIMESTAMP_OFFSET = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
        //生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
        private long SEQUENCE_MASK = ~(-1 << SEQUENCE_BITS);
        //工作节点ID(0~31)
        private long workerId;
        //数据中心ID(0~31)
        private long datacenterId;
        //毫秒内序列(0~4095)
        private long sequence = 0L;
        //上次生成ID的时间截
        private long lastTimestamp = -1L;
        public Snowflake1(long workerId, long datacenterId)
        {
            if (workerId > MAX_WORKER_ID || workerId < 0)
            {
                throw new ArgumentException(string.Format("WorkerID 不能大于 {0} 或小于 0", MAX_WORKER_ID));
            }
            if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0)
            {
                throw new ArgumentException(string.Format("DataCenterID 不能大于 {0} 或小于 0", MAX_DATACENTER_ID));
            }
            this.workerId = workerId;
            this.datacenterId = datacenterId;
        }
    }
}
